package org.persistent;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpUtil {

    /**
     * @author     : YY
     * @date       : 2018-7-6-上午11:25:01
     * @param      : @param urlStr
     * @param      : @param data
     * @param      : @return
     * @param      : @throws DocumentException
     * @Description: HTTP请求微信接口，返回map格式数据
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> postWx(String requestUrl, String outputStr) throws DocumentException {
        Logger logger = Logger.getLogger(Class.class);
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            //conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            if(buffer != null && buffer.toString().length() != 0){
                Map<String, String> preMap = new HashMap<String, String>();
                Document dom = DocumentHelper.parseText(buffer.toString());
                Element root = dom.getRootElement();
                List<Element> elementList = root.elements();
                for (Element e : elementList) {
                    preMap.put(e.getName(), e.getText());
                }
                return preMap;
            }
        } catch (Exception e) {
            logger.error("HTTP请求:["+requestUrl+"]异常： " + e.getMessage());
        }
        return null;
    }

}